/*
 * Copyright (C) 2009-2018 Hangzhou 2Dfire Technology Co., Ltd. All rights reserved
 */
package com.ws.soa.consumer.service;


import com.ws.soa.consumer.constant.Constants;
import com.ws.soa.consumer.dao.mapper.AccountMapper;
import com.ws.soa.consumer.domain.AccountDO;
import com.ws.soa.consumer.session.UserSessionStorage;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * SessionStorageClientService
 *
 * @author luobosi@2dfire.com
 * @since 2019-03-02
 */
@Service
public class SessionStorageClientService {

  @Resource
  private RedisCacheClientService redisCacheClientService;

  @Resource
  private AccountMapper accountMapper;


  /**
   * 获得 缓存在Session中的用户模型
   *
   * @param httpServletRequest request
   * @return UserSessionStorage
   */
  public UserSessionStorage getUserSessionStorage(HttpServletRequest httpServletRequest) {

    String token = httpServletRequest.getHeader("token");
    System.out.println("拿到的 header 里 信息:" + token);
    UserSessionStorage userSessionStorage = getUserSessionStorageByCache(token);
    if (null == userSessionStorage) {
      AccountDO accountDO = accountMapper.selectById(token);
      userSessionStorage = new UserSessionStorage();
      userSessionStorage.setMemberId(accountDO.getId());
      //userSessionStorage.setAppId(weChatConfig.getAppId());
      userSessionStorage.setNickName(accountDO.getUsername());
      userSessionStorage.setHeadUrl(accountDO.getAvatar());
      this.saveUserSessionStorage(accountDO.getId(), userSessionStorage);
    }
    System.out.println("缓存里面的用户信息：" + userSessionStorage.toString());
    return userSessionStorage;
  }

  public void saveUserSessionStorage(String memberId, UserSessionStorage userSessionStorage) {
    if (StringUtils.isBlank(memberId) || null == userSessionStorage) {
      return;
    }
    redisCacheClientService
        .setCache(Constants.CacheKey.WX_TOKEN_PREFIX + memberId, userSessionStorage,
                  Constants.Default.ONE_DAY);
  }


  private UserSessionStorage getAttribute(HttpServletRequest httpServletRequest) {
    return (UserSessionStorage) httpServletRequest.getAttribute(Constants.Session.SESSION_ID);
  }

  /**
   * 通过请求头x-auth-token获取当前用户的session
   *
   * @param httpServletRequest request
   * @return UserSessionStorage
   */
  private UserSessionStorage getSession(HttpServletRequest httpServletRequest) {
    String token = httpServletRequest.getParameter("token");
    if (StringUtils.isNotBlank(token)) {
      return getUserSessionStorageByCache(token);
    }
    return null;
  }

  private UserSessionStorage getUserSessionStorageByCache(String token) {
    Object obj = redisCacheClientService
            .getCache(Constants.CacheKey.WX_TOKEN_PREFIX + token, UserSessionStorage.class);
    return null == obj ? null : (UserSessionStorage) obj;
  }
}
